import { Column } from '@ant-design/charts';
import { ExclamationCircleOutlined, SearchOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { InputRef } from 'antd';
import { Result } from 'antd';
import { message } from 'antd';
import { Button, Card, Descriptions, Input, Tag } from 'antd';
import moment from 'moment';
import { useRef, useState } from 'react';
import { queryAnyIotSimInfo } from '../service';
import type { DahanSimInfo, TibiotSimInfo, UpiotSimInfo } from '../typings.d';
import { handleSupplier } from '../utils';

const OpenQuery = () => {
  const inputRef = useRef<InputRef>(null);
  const [upiotSimData, setUpiotSimData] = useState<UpiotSimInfo | null>(null);
  const [dahanSimData, setDahanSimData] = useState<DahanSimInfo | null>(null);
  const [tibiotSimData, setTibiotSimData] = useState<TibiotSimInfo | null>(null);
  const [usageLogData, setUsageLogData] = useState<{ value: number; time: string }[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [noCardWarning, setNoCardWarning] = useState(false);

  const renderUpiotCardStatus = (status: string) => {
    switch (status) {
      case '00':
        return <Tag color="green">使用中</Tag>;
      case '10':
        return <Tag color="green">测试期</Tag>;
      case '02':
        return <Tag color="red">已停机</Tag>;
      case '03':
        return <Tag color="red">预销号</Tag>;
      case '04':
        return <Tag color="pink">已销号</Tag>;
      case '11':
        return <Tag color="green">沉默期</Tag>;
      case '12':
        return <Tag color="red">停机保号</Tag>;
      case '99':
      default:
        return <Tag color="purple">未知</Tag>;
    }
  };

  const renderTibiotCardStatus = (status: string) => {
    switch (status) {
      case '1':
        return <Tag color="green">正常</Tag>;
      case '2':
        return <Tag color="red">停机</Tag>;
      case '3':
        return <Tag color="blue">待激活</Tag>;
      default:
        return <Tag color="purple">未知</Tag>;
    }
  };

  const onQuery = async () => {
    setDahanSimData(null);
    setTibiotSimData(null);
    setUpiotSimData(null);
    setUsageLogData([]);
    setNoCardWarning(false);
    const iv = inputRef.current?.input?.value;
    if (!iv) {
      message.warn({ key: 'open-query', content: '请输入要查询的流量卡号' });
      return;
    }
    setLoading(true);
    const res = await queryAnyIotSimInfo(iv);
    if (!res || !res.data || !res.success) {
      message.error({ key: 'open-query', content: res.message });
      setLoading(false);
      setNoCardWarning(true);
      return;
    }
    const { provider, info, flowData } = res.data;
    if (provider === 'dahan') {
      setDahanSimData(info);
    } else if (provider === 'tibiot') {
      setTibiotSimData(info);
    } else if (provider === 'upiot') {
      setUpiotSimData(info);
    }
    setUsageLogData(flowData);
    setLoading(false);
    return;
  };

  return (
    <PageHeaderWrapper header={{ title: '', subTitle: '流量卡开放查询' }}>
      <Card style={{ textAlign: 'center' }}>
        <Input
          ref={inputRef}
          placeholder="请输入要查询的流量卡号"
          style={{ width: '300px', marginRight: '20px' }}
          allowClear
          onPressEnter={onQuery}
        />
        <Button type="primary" onClick={onQuery}>
          查询
        </Button>
      </Card>
      {upiotSimData && (
        <Card title="基本信息">
          <Descriptions>
            <Descriptions.Item label="卡供应商">上海量讯</Descriptions.Item>
            <Descriptions.Item label="运营商">
              {handleSupplier({
                provider: 'upiot',
                info: upiotSimData,
                flowData: [],
              })}
            </Descriptions.Item>
            <Descriptions.Item label="短信下发">
              {upiotSimData.support_sms ? '支持' : '不支持'}
            </Descriptions.Item>
            <Descriptions.Item label="当前状态">
              {renderUpiotCardStatus(upiotSimData.account_status)}
            </Descriptions.Item>
            <Descriptions.Item label="激活时间">{upiotSimData.active_date}</Descriptions.Item>
            <Descriptions.Item label="到期时间">{upiotSimData.expiry_date}</Descriptions.Item>
            <Descriptions.Item label="套餐大小">{upiotSimData.data_plan} MB</Descriptions.Item>
            <Descriptions.Item label="当月流量">{upiotSimData.data_usage} MB</Descriptions.Item>
            <Descriptions.Item label="剩余流量">{upiotSimData.data_balance} MB</Descriptions.Item>
          </Descriptions>
        </Card>
      )}
      {dahanSimData && (
        <Card title="基本信息">
          <Descriptions>
            <Descriptions.Item label="卡供应商">大汉三通</Descriptions.Item>
            <Descriptions.Item label="运营商">
              {handleSupplier({
                provider: 'dahan',
                info: dahanSimData,
                flowData: [],
              })}
            </Descriptions.Item>
            <Descriptions.Item label="短信下发" span={2}>
              {dahanSimData.smsAbility === '1' ? '支持' : '不支持'}
            </Descriptions.Item>
            <Descriptions.Item label="激活时间">{dahanSimData.activeTime}</Descriptions.Item>
            <Descriptions.Item label="失效时间">
              {moment().add(Number(dahanSimData.leftDay), 'd').format('YYYY-MM-DD')}
            </Descriptions.Item>
            <Descriptions.Item label="套餐名称">
              {dahanSimData.flowPackage[0]?.pkgName}
            </Descriptions.Item>
            <Descriptions.Item label="套餐大小">{dahanSimData.totalFlow}</Descriptions.Item>
            <Descriptions.Item label="已用流量">{dahanSimData.usedFlow}</Descriptions.Item>
          </Descriptions>
        </Card>
      )}
      {tibiotSimData && (
        <Card title="基本信息">
          <Descriptions>
            <Descriptions.Item label="卡供应商">上海齐犇</Descriptions.Item>
            <Descriptions.Item label="运营商">
              {handleSupplier({
                provider: 'tibiot',
                info: tibiotSimData,
                flowData: [],
              })}
            </Descriptions.Item>
            <Descriptions.Item label="当前状态">
              {renderTibiotCardStatus(tibiotSimData.cardStatus)}
            </Descriptions.Item>
            <Descriptions.Item label="激活时间">{tibiotSimData.activateTime}</Descriptions.Item>
            <Descriptions.Item label="到期时间">{tibiotSimData.packageTime}</Descriptions.Item>
            <Descriptions.Item label="套餐名称">{tibiotSimData.packageName}</Descriptions.Item>
            <Descriptions.Item label="套餐大小">{tibiotSimData.totalFlow}</Descriptions.Item>
            <Descriptions.Item label="已用流量">{tibiotSimData.cardFlow}</Descriptions.Item>
          </Descriptions>
        </Card>
      )}

      {usageLogData.length > 0 && (
        <Card title="日流量统计">
          <div>
            <Column
              data={usageLogData}
              padding="auto"
              xField="time"
              yField="value"
              meta={{
                value: { alias: '流量(MB)' },
                time: { alias: '日期' },
              }}
              // yAxis={{ title: { text: '流量(MB)', position: 'end', autoRotate: false } }}
            />
          </div>
        </Card>
      )}

      {!dahanSimData && !upiotSimData && !tibiotSimData && (
        <Card>
          <Result
            icon={
              noCardWarning ? (
                <ExclamationCircleOutlined style={{ color: 'red' }} />
              ) : (
                <SearchOutlined />
              )
            }
            title={
              loading
                ? '查询中...'
                : (noCardWarning && '未找到目标流量卡') || '请输入流量卡号以进行查询'
            }
          />
        </Card>
      )}
    </PageHeaderWrapper>
  );
};

export default OpenQuery;
